package tech.aistar.corejava.xml;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import tech.aistar.corejava.xml.entity.Address;
import tech.aistar.corejava.xml.entity.Student;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:把内存中的java的集合写入到xml
 * @date 2019/8/7 0007
 */
public class Dom4jWriterStudent {

    public static void main(String[] args) {
        //模拟一些学生的集合
        List<Student> list = new ArrayList<>();
        Student s1 = new Student();
        s1.setId(1000);
        s1.setName("jack");
        s1.setNo("1009");
        s1.setBirthday(new Date());

        Address address = new Address();
        address.setProvince("安徽");
        address.setCity("滁州");

        s1.setAddress(address);

        list.add(s1);

        Student s2 = new Student();
        s2.setId(2000);
        s2.setName("tom");
        s2.setNo("1019");
        s2.setBirthday(new Date());

        list.add(s2);

        try {
            write(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void write(List<Student> studentList) throws IOException {
        //1. 获取Document
        Document document = DocumentHelper.createDocument();

        //2. 创建root根标签
        Element root = document.addElement("students");

        for (Student s : studentList) {
            //创建一个student标签
            Element stu = root.addElement("student");

            //student标签拥有id属性
            stu.addAttribute("id",String.valueOf(s.getId()));

            //分别创建student标签下的子标签
            Element nameElement = stu.addElement("name");
            //设置name标签中的值
            nameElement.setText(s.getName());

            stu.addElement("no").setText(s.getNo());

            stu.addElement("birthday").setText(String.format("%tF",s.getBirthday()));

            //判断是否创建address标签
            if(null!=s.getAddress()){
                Element addr = stu.addElement("address");

                //province和city
                addr.addElement("province").setText(s.getAddress().getProvince());
                addr.addElement("city").setText(s.getAddress().getCity());
            }
        }

        OutputFormat format = new OutputFormat("\t",true);

        //将准备好的document写出去
        XMLWriter out = new XMLWriter(new FileWriter("src/tech/aistar/corejava/xml/stu.xml"),format);
        out.write(document);
        out.flush();
        out.close();
        System.out.println("写出去成功!");
    }

}
